<template>
  <div class="modelStyle">
    <a-modal
      :maskClosable="false"
      v-model="isDeclareShow"
      title="申报房源"
      :width="930"
      class="jlw_model_title"
      destroyOnClose>
      <a-form :form="formHouse" >
        <a-row>
          <a-col :span="24" class="pad_bot10">房源地址</a-col>
        </a-row>
        <a-row>
          <a-col :span="16">
            <a-form-item>
              <a-cascader
                :options="administrativeRegion"
                popupClassName="noChilder"
                @change="onCityChange"
                placeholder="请选择城市"
                v-decorator="['xzxqbh', {
                  rules: [{ required: true, message: '必填'}]
                }
                ]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" class="pad_bot10 pad_top10">详细地址</a-col>
        </a-row>
        <a-row>
          <a-col :span="16" >
            <a-form-item>
              <a-input
                placeholder="请输入详细地址"
                v-decorator="['xxdz', {
                  rules: [{ required: true, message: '必填',whitespace: true}]
                }
                ]"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" class="pad_bot10 pad_top10">房屋类型</a-col>
        </a-row>
        <a-row>
          <a-col :span="16" >
            <a-form-item>
              <a-select
                v-decorator="['fwlx', {
                  rules: [{ required: true, message: '必填'}]
                }]"
                placeholder="请选择房屋类型">
                <a-select-option v-for="(item, index) in HOUSING_TYPE" :key="index" :value="item.status">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" class="pad_bot10 pad_top10">房间号</a-col>
        </a-row>
        <a-row>
          <template v-for="(i,index) in keys">
            <a-col :span="8" :key="i" v-if="computedDelObj[`${index}`] !=='true'">
              <a-row :gutter="18" style="height:64px;">
                <a-col :span="12">
                  <a-form-item>
                    <a-input
                      @blur="handleRoomNoBlur"
                      maxLength="10"
                      v-decorator="[`fh[${index}]`,{ rules: [{required: true,message: '请输入房间号'},{message: '不包含空格', pattern: spaceReg},{validator: validateRoomNo}],validateFirst:true}
                      ]"
                      placeholder="请输入房间号"/>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <div class="person" v-if="index === 0" @click="addTanentInfo"><a-icon :component="iconAddPerson" style="margin-top:12px;"/></div>
                  <div class="person" v-else @click="delTannetInfo(index)"><a-icon :component="iconDelPerson" style="margin-top:12px"/></div>
                </a-col>
              </a-row>
            </a-col>
          </template>
        </a-row>
      </a-form>
      <template slot="footer">
        <a-button type="primary" ghost @click="cancelDeclare">取消</a-button>
      </template>
      <template slot="footer">
        <a-popconfirm title="是否申报房源？" @confirm="handleSubmit" okText="确认" cancelText="取消">
          <a-button type="primary" class="primary_linear">申报房源</a-button>
        </a-popconfirm>
      </template>
    </a-modal>
  </div>
</template>
<script>
import { iconAddPerson, iconDelPerson } from '@/core/icons'
import { addHouses } from '@/api/houseResource'
import { verifyRepeat } from '@/utils/util'
import { mapGetters, mapActions } from 'vuex'
import { spaceReg } from '@/utils/reg'
import { HOUSING_TYPE } from '@/config/enum'
export default {
  name: 'DeclarationHousing',
  data () {
    return {
      HOUSING_TYPE, // 房屋类型
      keys: 1,
      spaceReg, // 匹配空格
      formHouse: this.$form.createForm(this),
      iconAddPerson, // 添加
      iconDelPerson, // 删除
      isDeclareShow: true, // 是否显示申报房源弹窗
      delObj: {} // 删除的数据
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'administrativeRegion', // 行政辖区（杭州）
      'STORE_ID',
      'OPERATOR_TYPE'
    ]),
    computedDelObj () {
      return this.delObj
    }
  },
  methods: {
    ...mapActions([
      'getAdministrativeRegion'
    ]),
    addTanentInfo () {
      this.keys += 1
    },
    // 用隐藏的方式(+计算属性)去减（不需要减key）
    delTannetInfo (index) {
      const selObj = { }
      selObj[index] = 'true'
      this.delObj = Object.assign(selObj, this.delObj)
      // 删除自动校验
      this.$nextTick(() => {
        const form = this.formHouse
        const selArray = form.getFieldValue('fh')
        for (let i = 0; i < selArray.length; i++) {
          if (selArray[i]) {
            form.validateFields([`fh[${i}]`], { force: true })
          }
        }
      })
      // const form = this.formHouse
      // const fhArray = form.getFieldValue('fh')
      // const filterFh = fhArray.filter((item, itemIndex) => {
      //   if (index !== itemIndex) {
      //     return true
      //   }
      // })
      // filterFh.forEach((item, itemIndex) => {
      //   form.setFieldsValue({ [`fh[${itemIndex}]`]: item })
      // })
      // this.keys -= 1
    },
    onCityChange (value, selOption) {
    },
    handleSubmit () {
      this.formHouse.validateFieldsAndScroll((err, values) => {
        if (!err) {
          const params = Object.assign({}, values)
          // 过滤由删除影藏导致的无用数组索引
          const filterFh = params['fh'].filter((item) => {
            if (item) {
              return true
            }
          })
          params.fh = filterFh
          // end
          params.hoperatorId = this.userInfo.id
          params.storesId = this.STORE_ID
          params.jylx = this.OPERATOR_TYPE // 门店所属经营类型
          const xzxqbhArray = values['xzxqbh']
          params.xzxqbh = xzxqbhArray[xzxqbhArray.length - 1]
          addHouses(params).then((res) => {
            this.formHouse.resetFields()
            this.isDeclareShow = false
            this.$notification['success']({
              message: this.$t('message.successTitle'),
              description: this.$t('message.declaration'),
              duration: 10
            })
            // 备注暂时不更新列表，因为申报成功不显示在列表，只有审核通过才显示
            // this.$parent.$parent.searchAjax()
          }).catch((res) => {
            console.log('request.js统一处理错误')
          })
        }
      })
    },
    handleRoomNoBlur (e) {
      const form = this.formHouse
      const selArray = form.getFieldValue('fh')
      for (let i = 0; i < selArray.length; i++) {
        if (selArray[i]) {
          if (e.target.id !== `fh[${i}]` && e.target.value) {
            form.validateFields([`fh[${i}]`], { force: true })
          }
        }
      }
    },
    validateRoomNo (rule, value, callback) {
      const formt = this.formHouse
      const fhArray = formt.getFieldValue('fh')
      if (value && fhArray.length > 0) {
        const istrue = verifyRepeat(fhArray, value, rule.field, 2)
        if (istrue === true) {
          callback(new Error('房号不能重复'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    cancelDeclare () {
      this.isDeclareShow = false
    },
    openDeclare () {
      this.isDeclareShow = true
      this.keys = 1
    }
  },
  created () {
    if (!this.administrativeRegion.length > 0) {
      this.getAdministrativeRegion()
    }
  }
}
</script>
<style lang="less" scoped>
.person {
  cursor: pointer;
  color: #1890FF;
}
</style>
